﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web;
using System.Xml;
using WsdlConverter;

namespace svcutil2
{
    public class Wsdl2Listener
    {
        private string url;

        private HttpListenerContext context;
        private HttpListener listener;
        private Thread listenerThread;

        public Wsdl2Listener(string url)
        {
            this.url = url; 
        }

        public void Start()
        {
            this.listener = new HttpListener();
            this.listener.Prefixes.Add(this.url);

            this.listener.Start();

            this.listenerThread = new Thread(this.Listen);
            this.listenerThread.Start();
        }


        public void Stop()
        {
            this.listener.Close();

            this.listenerThread.Abort();
        }

        public void Listen()
        {
            try
            {
                while (true)
                {
                    context = this.listener.GetContext();
                    HandleRequest();
                }
            }
            catch (Exception e)
            {

            }
        }

        private void HandleRequest()
        {
            context.Response.ContentType = "text/xml";

            try
            {             
                string originalUrl = GetOriginalUrl();

                var originalWsdl = new WebClient().DownloadData(originalUrl);

                var wsdl2 = new XmlDocument();
                wsdl2.Load(new MemoryStream(originalWsdl));

                var converter = new Wsdl2WsdlConverter();
                converter.DocumentReference += converter_DocumentReference;
                var res = converter.Convert(wsdl2);
                
                res.Write(context.Response.OutputStream);
                
            }
            catch (Exception e)
            {
                context.Response.StatusCode = 500;
            }

            context.Response.OutputStream.Close();
        }

        private string GetOriginalUrl()
        {
            var originalUrl = this.context.Request.Url.Query.Substring(1);
            originalUrl = HttpUtility.UrlDecode(originalUrl);
            return originalUrl;
        }

        void converter_DocumentReference(object source, ref string url)
        {
            string originalUrl = GetOriginalUrl();

            var original = new Uri(new Uri(Environment.CurrentDirectory + @"\"), originalUrl);
            var uri = new Uri(original, url);
            url = String.Format("{0}?{1}", this.url, uri);
        }

    }
}
